<?php
namespace app\home\controller;
use think\Controller;
use think\Db;	
use think\Session;
use think\request;

/**
 *
 * 阿里支付控制器
 */
class Alinotify extends Controller{
	/**
	 * 支付结果异步回调
	 */
	public function aliNotify(){
		 file_put_contents('ass01.txt',json_encode($_POST));
		require_once EXTEND_PATH.'/alipays/config.php';
		require_once EXTEND_PATH.'/alipays/pagepay/service/AlipayTradeService.php';
		$arr=$_POST;
		$alipaySevice = new \AlipayTradeService($config); 
		$alipaySevice->writeLog(var_export($_POST,true));
		$result = $alipaySevice->check($arr);
		file_put_contents('ass02.txt',json_encode($_POST));
		if($result){
		file_put_contents('ass03.txt',json_encode($_POST));
			$out_trade_no = $_POST['out_trade_no'];//商户订单号
			$trade_status = $_POST['trade_status'];
			$trade_no = $_POST['trade_no'];//支付宝交易号
			if($_POST['trade_status'] == 'TRADE_SUCCESS') {
				$res = Db::name('user_recharge')->where(['tradeNo'=>$out_trade_no])->find();
				//支付宝交易号
				if($res&&$res['paymentstate']==0){
					//启动事务    
		       		Db::startTrans();
		         	try{ 
					$cashlog = Db::name('cashlog')->where(['uid'=>$res['uid']])->order('id','desc')->find();
					$user = Db::name('users')->where(['id'=>$res['uid']])->find();
					$cas = [
						'uid'=>$res['uid'],
						'type'=>1,
						'price'=>$res['amount'],
						'time'=>date('Y-m-d H:i:s'),
						'balance'=>$cashlog['balance']+$res['amount'],
					];	 
			
						Db::name('users')->where(['id'=>$res['uid']])->update(['balance'=>$user['balance']+$res['amount']]);
						Db::name('user_recharge')->where('id',$res['id'])->update(['paymentstate'=>1,'paymenttime'=>date('Y-m-d H:i:s'),'platformtradeNo'=>$arr['trade_no']]);
						Db::name('cashlog')->insert($cas);
						//提交事务
		            	Db::commit();
		          	}catch (\Exception $e) {
		                // 回滚事务
		                Db::rollback();
		                echo 'error';
		            }       
		            echo 'success';
				}else{
					echo 'error';
				}
			}else{
				echo 'error';
			}
		}else{
			echo 'error';
		}
	}


}